﻿//-----------------------------------------------------------------------
// <copyright file="CustomBinaryWriter.cs" company="None">
// None
// </copyright>
//-----------------------------------------------------------------------

namespace WCFDataServiceFormatExtensions
{
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Xml;

    /// <summary>
    /// Custom binary writer class for writing WCF binary messages body.
    /// </summary>
    public class CustomBinaryWriter : BodyWriter
    {
        /// <summary>
        /// Content to write.
        /// </summary>
        private string content;

        /// <summary>
        /// Initializes a new instance of the CustomBinaryWriter class.
        /// </summary>
        /// <param name="content">Content to write</param>
        public CustomBinaryWriter(string content, Encoding encoding)
            : base(false)
        {
            this.content = content;
            this.encoding = encoding;
        }

        Encoding encoding;
        /// <summary>
        /// Called by service implementatio. 
        /// </summary>
        /// <param name="writer">XmlDictionaryWriter instance provided by service.</param>
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Binary");
            byte[] buffer = this.encoding.GetBytes(this.content);
            writer.WriteBase64(buffer, 0, buffer.Length);
            writer.WriteEndElement();
        }
    }
}